const { z } = require('zod');

const rawConfig = {
  NODE_ENV: process.env.NODE_ENV ?? 'development',
  PORT: process.env.PORT ?? '4000',
  HOST: process.env.HOST ?? '0.0.0.0',
  SUPERDB_API_KEY: process.env.SUPERDB_API_KEY ?? '',
  ALLOW_ORIGINS: process.env.ALLOW_ORIGINS ?? '*',
  RATE_LIMIT_WINDOW_MS: process.env.RATE_LIMIT_WINDOW_MS ?? '60000',
  RATE_LIMIT_MAX: process.env.RATE_LIMIT_MAX ?? '60',
  LOG_LEVEL: process.env.LOG_LEVEL ?? 'info',
  DATA_BACKEND: process.env.DATA_BACKEND ?? 'memory',
  DATABASE_URL: process.env.DATABASE_URL ?? '',
  VECTOR_DIMENSION: process.env.VECTOR_DIMENSION ?? '1536',
  EMBEDDING_PROVIDER: process.env.EMBEDDING_PROVIDER ?? 'mock',
  OPENAI_API_KEY: process.env.OPENAI_API_KEY ?? '',
  AZURE_OPENAI_ENDPOINT: process.env.AZURE_OPENAI_ENDPOINT ?? '',
  AZURE_OPENAI_API_KEY: process.env.AZURE_OPENAI_API_KEY ?? '',
  AZURE_OPENAI_DEPLOYMENT: process.env.AZURE_OPENAI_DEPLOYMENT ?? '',
  OLLAMA_BASE_URL: process.env.OLLAMA_BASE_URL ?? 'http://localhost:11434'
};

const schema = z.object({
  NODE_ENV: z.string(),
  PORT: z.coerce.number().int().positive(),
  HOST: z.string().min(1),
  SUPERDB_API_KEY: z.string().optional(),
  ALLOW_ORIGINS: z.string().min(1),
  RATE_LIMIT_WINDOW_MS: z.coerce.number().int().positive(),
  RATE_LIMIT_MAX: z.coerce.number().int().positive(),
  LOG_LEVEL: z.string().min(1),
  DATA_BACKEND: z.enum(['memory', 'postgres']).default('memory'),
  DATABASE_URL: z.string().optional(),
  VECTOR_DIMENSION: z.coerce.number().int().positive().default(1536),
  EMBEDDING_PROVIDER: z.string().min(1),
  OPENAI_API_KEY: z.string().optional(),
  AZURE_OPENAI_ENDPOINT: z.string().optional(),
  AZURE_OPENAI_API_KEY: z.string().optional(),
  AZURE_OPENAI_DEPLOYMENT: z.string().optional(),
  OLLAMA_BASE_URL: z.string().optional()
});

const parsed = schema.safeParse(rawConfig);

if (!parsed.success) {
  console.error('Failed to parse configuration:', parsed.error.flatten().fieldErrors);
  process.exit(1);
}

const data = parsed.data;
const fallbackKey = data.SUPERDB_API_KEY && data.SUPERDB_API_KEY.trim().length > 0
  ? data.SUPERDB_API_KEY.trim()
  : data.NODE_ENV === 'development' || data.NODE_ENV === 'test'
    ? 'dev-superdb-key'
    : '';

const config = {
  env: data.NODE_ENV,
  port: data.PORT,
  host: data.HOST,
  apiKey: fallbackKey,
  allowOrigins: data.ALLOW_ORIGINS,
  rateLimit: {
    windowMs: data.RATE_LIMIT_WINDOW_MS,
    max: data.RATE_LIMIT_MAX
  },
  logLevel: data.LOG_LEVEL,
  requireApiKey: fallbackKey.length > 0,
  dataBackend: data.DATA_BACKEND,
  databaseUrl: data.DATABASE_URL,
  vectorDimension: data.VECTOR_DIMENSION,
  embeddingProvider: data.EMBEDDING_PROVIDER,
  providers: {
    openai: { apiKey: data.OPENAI_API_KEY },
    azure: {
      endpoint: data.AZURE_OPENAI_ENDPOINT,
      apiKey: data.AZURE_OPENAI_API_KEY,
      deployment: data.AZURE_OPENAI_DEPLOYMENT
    },
    ollama: {
      baseUrl: data.OLLAMA_BASE_URL
    }
  }
};

if (config.dataBackend === 'postgres' && !config.databaseUrl) {
  console.error('DATABASE_URL is required when DATA_BACKEND=postgres');
  process.exit(1);
}

module.exports = { config };
